// 计算校验和
function calculateChecksum(data) {
    console.log([data.DataType,data.Fixed,data.DataNo1,data.DataNo2].concat(data.Data),'校验数据')
    const arr = [data.DataType,data.Fixed,data.DataNo1,data.DataNo2].concat(data.Data)
    let sum = 0;
    for (let i = 0; i < arr.length; i++) {
      sum += arr[i];
      sum = sum & 0xFF;
    }
    let checksum =  sum ^ 0xFF;
    console.log(checksum,'校验和')
    console.log(checksum.toString(16),'校验和16进制')
    return checksum;
}

// 数据包装发送
export const createBuffer2 = (total, DataType, Fixed , DataNo1 ,DataNo2, Data) => {
    let buffer = new ArrayBuffer(total)
    let dataView = new DataView(buffer)
    // Head Code
    dataView.setUint8(0, 0x2E)

    dataView.setUint8(1, DataType)
    dataView.setUint8(2, Fixed)
    dataView.setUint8(3, DataNo1)
    dataView.setUint8(4, DataNo2)
    // Data
    if (Data && Data.length) {
        Data.forEach((el, index) => {
            dataView.setUint8(index + 5, el)
        })
    }
    // SUM
    const SUM = calculateChecksum({
        DataType: DataType,
        Fixed:Fixed,
        DataNo1:DataNo1,
        DataNo2:DataNo2,
        Data: Data
    })

    dataView.setUint8(total - 1,SUM)

    console.log(dataView,'dataViewdataViewdataView')

    return buffer
}
